﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DunLibrary.Query;
using DunSilverlight.Comm;
using DunLibrary.Dun;
using DunSilverlight.ViewModel;
using Telerik.Windows.Controls.Charting;

namespace DunSilverlight.Views
{
    public partial class Index : Page
    {
        public Index()
        {
            InitializeComponent();

            #region  设置chart属性,因为在xaml中设置会出现问题（暂时不明白），所以采用代码方式
            rc.DefaultView.ChartLegend.Background = new SolidColorBrush(Colors.Transparent);
            rc.DefaultView.ChartLegend.BorderThickness = new Thickness(0);
            rc.DefaultView.ChartLegend.Header = "";
            rc.DefaultView.ChartArea.AxisX.DefaultLabelFormat = "#VAL{yy年M月}";
            rc.DefaultView.ChartArea.AxisX.Step = 1;
            rc.DefaultView.ChartArea.AxisY.ExtendDirection = AxisExtendDirection.Up;
            rc.DefaultView.ChartArea.AxisY.MinorTicksVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.MajorTicksVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            rc.DefaultView.ChartArea.AxisY.PlotAreaAxisVisibility = Visibility.Collapsed;
            #endregion
        }

    

        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            LoadAmountReturn();
            LoadAgree();
            LoadVisitRecord();
            LoadInv();
        }

        private void LoadAmountReturn()
        {
            //需要统计的月数（最近）
            const int monthCountForStatistic = 6;
            List<DateTime> dateTimeList = new List<DateTime>();
            List<string> yearPeriodList = new List<string>();

            ArrearRecordService.ArrearRecordServiceClient ser = new ArrearRecordService.ArrearRecordServiceClient();
            ser.GetListBySQLCompleted += (sender, e) =>
            {
                List<List<LineChartModel>> values = new List<List<LineChartModel>>();
                values.Add(new List<LineChartModel>()); //完成回款
                values.Add(new List<LineChartModel>()); //未完成回款

                int total = 0;
                var objList = JsonSerializerHelper.JsonToEntities<object[]>(e.Result, out total);
                
                for (int i = 0; i < monthCountForStatistic; i++)
                {
                    //完成回款
                    LineChartModel item1 = new LineChartModel();
                    item1.Time = dateTimeList[i];
                    item1.Value = 0;

                    //未完成回款
                    LineChartModel item2 = new LineChartModel();
                    item2.Time = dateTimeList[i];
                    item2.Value = 0;

                    var obj = objList.SingleOrDefault(c => c[0].ToString() == yearPeriodList[i]);
                    if (obj != null)
                    {
                        item1.Value = int.Parse(obj[1].ToString());
                        item2.Value = int.Parse(obj[2].ToString());
                    }

                    values[0].Add(item1);
                    values[1].Add(item2);
                }

                runTotal.Text = string.Format("总的催款数：{0}件", values[0][monthCountForStatistic - 1].Value + values[1][monthCountForStatistic - 1].Value);
                runNot.Text = string.Format("未完成回款数：{0}件", values[1][monthCountForStatistic - 1].Value);

                totalInfo.Visibility = Visibility.Visible;

                #region 设置 chart 和 数据 的绑定关系，因为在xaml中设置会出现问题（暂时不明白），所以采用代码方式
                rc.SeriesMappings.Clear();
                rc.ItemsSource = null;
                rc.DefaultView.ChartArea.EnableAnimations = true;
                rc.DefaultView.ChartLegend.Header = "最近6个月回款数据对比";

                SeriesMapping mapping = new SeriesMapping();
                mapping.LegendLabel = "完成回款（单位：银行卡）";
                mapping.CollectionIndex = 0;
                SplineSeriesDefinition def = new SplineSeriesDefinition();
                def.ItemLabelFormat = "0.#";
                def.ShowItemLabels = true;
                mapping.SeriesDefinition = def;
                mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
                mapping.ItemMappings.Add(new ItemMapping("Time", DataPointMember.XCategory));
                rc.SeriesMappings.Add(mapping);

                mapping = new SeriesMapping();
                mapping.LegendLabel = "未完成回款（单位：银行卡）";
                mapping.CollectionIndex = 1;
                def = new SplineSeriesDefinition();
                def.ItemLabelFormat = "0.#";
                def.ShowItemLabels = true;
                mapping.SeriesDefinition = def;
                mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
                mapping.ItemMappings.Add(new ItemMapping("Time", DataPointMember.XCategory));
                rc.SeriesMappings.Add(mapping);
                #endregion

                rc.ItemsSource = values;
            };

            DateTime now = DateTime.Now;
            
            for (int i = 0; i < monthCountForStatistic; i++)
            {
                dateTimeList.Add(now.AddMonths(-5+i));
                yearPeriodList.Add(dateTimeList[i].ToString("yyyyMM"));
            }

            string sqlInStr = string.Join(",", yearPeriodList);
            string orgNum = null;
            if (AppGlobal.CurrentUser.Organization != null)
                orgNum = AppGlobal.CurrentUser.Organization.FullNumber;

            string operCondition = "";
            if (!RightManagement.VerifyRight(RightManagement.Right_View_All_Case))
            {
                operCondition = " and b.OperId = " + AppGlobal.CurrentUser.Id;
            }

            string sql = string.Format(@"select t1.YearPeriod,t1.total Total,isnull(t2.qty,0) Qty1,isnull(t3.qty,0) Qty2
                            from
                            (
	                            select a.YearPeriod,COUNT(*) total from Dun_ArrearRecord a
	                            join Dun_Case b on a.CaseId=b.Id
	                            join User_User u on b.OperId = u.Id
	                            join Organization_Organization org on u.OrganizationId=org.Id
	                            where a.YearPeriod in (201108,201109,201110,201111,201112,201201)
	                            and (org.FullNumber like '{1}' or org.FullNumber = '{2}') {3}
	                            group by a.YearPeriod
                            ) t1
                            left join
                            (
	                            select a.YearPeriod,COUNT(*) qty from Dun_ArrearRecord a
	                            join Dun_Case b on a.CaseId=b.Id
	                            join User_User u on b.OperId = u.Id
	                            join Organization_Organization org on u.OrganizationId=org.Id
	                            where a.YearPeriod in ({0})
	                            and a.Amount<=a.TotalReturnAmount
	                            and (org.FullNumber like '{1}' or org.FullNumber = '{2}') {3}
	                            group by a.YearPeriod
                            ) t2 on t1.YearPeriod=t2.YearPeriod
                            left join
                            (
	                            select a.YearPeriod,COUNT(*) qty from Dun_ArrearRecord a
	                            join Dun_Case b on a.CaseId=b.Id
	                            join User_User u on b.OperId = u.Id
	                            join Organization_Organization org on u.OrganizationId=org.Id
	                            where a.YearPeriod in ({0})
	                            and a.Amount > a.TotalReturnAmount
	                            and (org.FullNumber like '{1}' or org.FullNumber = '{2}') {3}
	                            group by a.YearPeriod

                            ) t3 on t1.YearPeriod=t3.YearPeriod
                            order by t1.YearPeriod", sqlInStr, string.Format("%{0}.%", orgNum), orgNum, operCondition);
            ser.GetListBySQLAsync(sql);
        }


        private void LoadAgree()
        {
            CallRecordService.CallRecordServiceClient ser = new CallRecordService.CallRecordServiceClient();

            ser.GetListByHQLWithPagingCompleted += (object sender, CallRecordService.GetListByHQLWithPagingCompletedEventArgs e) =>
                {
                    try
                    {
                        int totalCount = 0;
                        IList<CallRecord> records = JsonSerializerHelper.JsonToEntities<CallRecord>(e.Result, out totalCount);
                        dgdAgree.ItemsSource = records;
                    }
                    catch (Exception ex)
                    {
                        Tools.ShowMessage(ex.Message, "", false);
                    }

                };

            string beginTime=DateTime.Now.ToShortDateString();
            string endTime=DateTime.Now.AddDays(5).ToShortDateString();

            string orgNumber=AppGlobal.CurrentUser.Organization.FullNumber+"%";

            string hql = null;
            string totalHql = null;

            if (RightManagement.VerifyRight(RightManagement.Right_View_All_Case))
            {
                hql = string.Format("from CallRecord as c where c.Case.BranchCompany.FullNumber Like '{0}' and c.IsAgree=true and c.AgreeTime>='{1}' and c.AgreeTime<='{2}'", orgNumber, beginTime, endTime);
                totalHql = string.Format("select count(*) from CallRecord as c where c.Case.BranchCompany.FullNumber Like '{0}' and c.IsAgree=true and c.AgreeTime>='{1}' and c.AgreeTime<='{2}'", orgNumber, beginTime, endTime);
            }
            else
            {
                hql = string.Format("from CallRecord as c where c.Case.BranchCompany.FullNumber Like '{0}' and c.IsAgree=true and c.AgreeTime>='{1}' and c.AgreeTime<='{2}' and c.Case.Oper.Id={3}", orgNumber, beginTime, endTime,AppGlobal.CurrentUser.Id);
                totalHql = string.Format("select count(*) from CallRecord as c where c.Case.BranchCompany.FullNumber Like '{0}' and c.IsAgree=true and c.AgreeTime>='{1}' and c.AgreeTime<='{2}' and c.Case.Oper.Id={3}", orgNumber, beginTime, endTime,AppGlobal.CurrentUser.Id);
            }

            QueryCondition qc=new QueryCondition();
            qc.FirstResult=0;
            qc.MaxResults=19;
            qc.HQL=hql;
            qc.TotalHQL=totalHql;

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(qc);

            ser.GetListByHQLWithPagingAsync(json);

        }

        /// <summary>
        /// 将 201111 转换成日期格式的 2011 11 1
        /// </summary>
        /// <param name="yearPeriod"></param>
        /// <returns></returns>
        private DateTime yearPeriodTransfer(int yearPeriod)
        {
            int year = yearPeriod / 100;
            int month = yearPeriod % 100;
            return new DateTime(year, month, 1);
        }

        /// <summary>
        /// 读取最近一个月外放
        /// </summary>
        private void LoadVisitRecord()
        {
            VisitRecordService.VisitRecordServiceClient ser = new VisitRecordService.VisitRecordServiceClient();
            ser.GetListByHQLCompleted += (sender, e) =>
                {
                    int totalCount=0;
                    IList<VisitRecord> rec = JsonSerializerHelper.JsonToEntities<VisitRecord>(e.Result, out totalCount);

                    dgdVisit.ItemsSource = rec;
                };
            string beginTime=DateTime.Now.AddDays(-30).ToShortDateString();
            string endTime=DateTime.Now.AddDays(1).ToShortDateString();//要加一天!
            int userId=AppGlobal.CurrentUser.Id;

            string hql = string.Format("from VisitRecord as v where v.OperateTime>='{0}' and v.OperateTime<='{1}' and (v.Case.Oper.Id={2} or v.Checker.Id={3}) order by v.OperateTime desc", beginTime, endTime, userId, userId);

            ser.GetListByHQLAsync(hql);

        }
        /// <summary>
        /// 读取最近一个月的调查申请
        /// </summary>
        private void LoadInv()
        {
            InvRequestService.InvestigateRequestServiceClient ser = new InvRequestService.InvestigateRequestServiceClient();

            ser.GetListByHQLCompleted += (sender, e) =>
                {
                    int totalCount = 0;
                    IList<InvestigateRequest> rec = JsonSerializerHelper.JsonToEntities<InvestigateRequest>(e.Result, out totalCount);
                    dgdInv.ItemsSource = rec;
                };

            string beginTime = DateTime.Now.AddDays(-30).ToShortDateString();
            string endTime = DateTime.Now.AddDays(1).ToShortDateString();//要加一天!
            int userId = AppGlobal.CurrentUser.Id;

            string hql = string.Format("from InvestigateRequest as inv where inv.OperateTime>='{0}' and inv.OperateTime<='{1}' and (inv.Case.Oper.Id={2} or inv.Checker.Id={3}) order by inv.OperateTime desc", beginTime, endTime, userId, userId);

            ser.GetListByHQLAsync(hql);
        }

    }

    

    public class TestData
    {
        public string Name { get; set; }
        public DateTime Date
        {
            get;
            set;
        }
        public int Value { get; set; }
        public int Value2 { get; set; }
        public int Value3 { get; set; }


        public string Number { get; set; }
        public string Number1 { get; set; }
    }
}
